<template>
  <el-dialog
    v-model="visible"
    title="失物详情"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading" class="detail-container">
      <el-row :gutter="20" v-if="itemDetail">
        <!-- 左侧：图片展示 -->
        <el-col :span="12">
          <div class="image-gallery">
            <el-carousel :interval="4000" indicator-position="outside">
              <el-carousel-item v-for="(img, index) in itemDetail.images" :key="index">
                <el-image :src="img" fit="contain" :preview-src-list="itemDetail.images" />
              </el-carousel-item>
            </el-carousel>
          </div>
        </el-col>

        <!-- 右侧：详细信息 -->
        <el-col :span="12">
          <div class="detail-info">
            <h2 class="detail-title">{{ itemDetail.title }}</h2>
            
            <el-tag :type="getStatusType(itemDetail.status)" size="large">
              {{ getStatusText(itemDetail.status) }}
            </el-tag>

            <el-descriptions :column="1" border class="detail-desc">
              <el-descriptions-item label="物品类别">
                {{ itemDetail.category }}
              </el-descriptions-item>
              <el-descriptions-item label="拾取地点">
                <el-icon><Location /></el-icon>
                {{ itemDetail.location }}
              </el-descriptions-item>
              <el-descriptions-item label="拾取时间">
                <el-icon><Clock /></el-icon>
                {{ formatDateTime(itemDetail.foundTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="发布者">
                <div class="user-info">
                  <el-avatar :src="itemDetail.userAvatar" :size="24">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <span>{{ itemDetail.userName }}</span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="物品描述">
                <div class="description">{{ itemDetail.description }}</div>
              </el-descriptions-item>
            </el-descriptions>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button
                :type="itemDetail.isLiked ? 'danger' : 'primary'"
                :icon="itemDetail.isLiked ? StarFilled : Star"
                @click="handleLike"
              >
                {{ itemDetail.isLiked ? '已点赞' : '点赞' }} ({{ itemDetail.likeCount }})
              </el-button>
              
              <el-button
                v-if="itemDetail.status === 0"
                type="success"
                :icon="Checked"
                @click="showClaimDialog = true"
              >
                申请领取
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 评论区域 -->
      <div class="comment-section" v-if="itemDetail">
        <el-divider>评论区 ({{ itemDetail.commentCount }})</el-divider>

        <!-- 发表评论 -->
        <div class="add-comment">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="发表你的评论..."
            maxlength="500"
            show-word-limit
          />
          <el-button
            type="primary"
            :loading="commentLoading"
            @click="handleAddComment"
            style="margin-top: 10px"
          >
            发表评论
          </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div
            v-for="comment in commentList"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-header">
              <div class="comment-user">
                <el-avatar :src="comment.userAvatar" :size="36">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <div class="user-meta">
                  <span class="user-name">{{ comment.userName }}</span>
                  <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
                </div>
              </div>
              <div class="comment-actions">
                <el-button
                  text
                  :type="comment.isLiked ? 'danger' : ''"
                  @click="handleLikeComment(comment)"
                >
                  <el-icon><StarFilled v-if="comment.isLiked" /><Star v-else /></el-icon>
                  {{ comment.likeCount }}
                </el-button>
                <el-button text @click="handleShowReply(comment)">
                  <el-icon><ChatDotRound /></el-icon>
                  回复
                </el-button>
              </div>
            </div>
            
            <div class="comment-content">{{ comment.content }}</div>

            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
              <div
                v-for="reply in comment.replies"
                :key="reply.id"
                class="reply-item"
              >
                <div class="reply-header">
                  <el-avatar :src="reply.userAvatar" :size="28">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <span class="reply-user">{{ reply.userName }}</span>
                  <span v-if="reply.replyToUserName" class="reply-to">
                    回复 @{{ reply.replyToUserName }}
                  </span>
                  <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                  <el-button
                    text
                    size="small"
                    :type="reply.isLiked ? 'danger' : ''"
                    @click="handleLikeReply(reply)"
                  >
                    <el-icon><StarFilled v-if="reply.isLiked" /><Star v-else /></el-icon>
                    {{ reply.likeCount }}
                  </el-button>
                </div>
                <div class="reply-content">{{ reply.content }}</div>
              </div>
            </div>

            <!-- 回复输入框 -->
            <div v-if="currentReplyComment?.id === comment.id" class="reply-input">
              <el-input
                v-model="replyContent"
                type="textarea"
                :rows="2"
                :placeholder="`回复 @${comment.userName}...`"
                maxlength="200"
              />
              <div class="reply-buttons">
                <el-button size="small" @click="currentReplyComment = null">
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  :loading="replyLoading"
                  @click="handleAddReply(comment)"
                >
                  发送
                </el-button>
              </div>
            </div>
          </div>

          <!-- 加载更多 -->
          <el-button
            v-if="hasMoreComments"
            text
            @click="loadMoreComments"
            class="load-more"
          >
            加载更多评论
          </el-button>
        </div>
      </div>
    </div>

    <!-- 申请领取对话框 -->
    <el-dialog
      v-model="showClaimDialog"
      title="申请领取"
      width="500px"
      append-to-body
    >
      <el-form :model="claimForm" label-width="80px">
        <el-form-item label="联系方式" required>
          <el-input v-model="claimForm.contactInfo" placeholder="请输入您的联系方式" />
        </el-form-item>
        <el-form-item label="申领理由" required>
          <el-input
            v-model="claimForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请说明您为什么要申领此物品"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showClaimDialog = false">取消</el-button>
        <el-button type="primary" :loading="claimLoading" @click="handleClaim">
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Location,
  Clock,
  User,
  Star,
  StarFilled,
  Checked,
  ChatDotRound
} from '@element-plus/icons-vue'
import {
  reqLostItemDetail,
  reqLikeItem,
  reqUnlikeItem,
  reqClaimItem,
  reqCommentList,
  reqAddComment,
  reqAddReply,
  reqLikeComment,
  reqUnlikeComment,
  reqLikeReply,
  reqUnlikeReply
} from '@/api/lost'
import type { LostItem, Comment, Reply } from '@/api/lost/type'
import dayjs from 'dayjs'

interface Props {
  modelValue: boolean
  itemId: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 失物详情
const itemDetail = ref<LostItem | null>(null)
const loading = ref(false)

// 评论相关
const commentList = ref<Comment[]>([])
const commentContent = ref('')
const commentLoading = ref(false)
const commentPage = ref(1)
const hasMoreComments = ref(false)

// 回复相关
const currentReplyComment = ref<Comment | null>(null)
const replyContent = ref('')
const replyLoading = ref(false)

// 申领相关
const showClaimDialog = ref(false)
const claimLoading = ref(false)
const claimForm = ref({
  contactInfo: '',
  reason: ''
})

// 获取失物详情
const getItemDetail = async () => {
  if (!props.itemId || loading.value) return
  
  loading.value = true
  try {
    const result = await reqLostItemDetail(props.itemId)
    if (result.code === 200) {
      itemDetail.value = result.data
      // 同时获取评论列表
      getCommentList()
    } else {
      ElMessage.error(result.message || '获取详情失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const getCommentList = async (page = 1) => {
  try {
    const result = await reqCommentList(props.itemId, page, 10)
    if (result.code === 200) {
      if (page === 1) {
        commentList.value = result.data.records
      } else {
        commentList.value.push(...result.data.records)
      }
      commentPage.value = page
      hasMoreComments.value = commentList.value.length < result.data.total
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取评论失败')
  }
}

// 加载更多评论
const loadMoreComments = () => {
  getCommentList(commentPage.value + 1)
}

// 点赞/取消点赞
const handleLike = async () => {
  if (!itemDetail.value) return
  
  try {
    if (itemDetail.value.isLiked) {
      await reqUnlikeItem(itemDetail.value.id)
      itemDetail.value.isLiked = false
      itemDetail.value.likeCount--
      ElMessage.success('取消点赞')
    } else {
      await reqLikeItem(itemDetail.value.id)
      itemDetail.value.isLiked = true
      itemDetail.value.likeCount++
      ElMessage.success('点赞成功')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 发表评论
const handleAddComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  commentLoading.value = true
  try {
    const result = await reqAddComment({
      itemId: props.itemId,
      content: commentContent.value
    })
    if (result.code === 200) {
      ElMessage.success('评论成功')
      commentContent.value = ''
      // 重新获取评论列表
      getCommentList(1)
      // 更新评论数
      if (itemDetail.value) {
        itemDetail.value.commentCount++
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '评论失败')
  } finally {
    commentLoading.value = false
  }
}

// 点赞/取消点赞评论
const handleLikeComment = async (comment: Comment) => {
  try {
    if (comment.isLiked) {
      await reqUnlikeComment(comment.id)
      comment.isLiked = false
      comment.likeCount--
    } else {
      await reqLikeComment(comment.id)
      comment.isLiked = true
      comment.likeCount++
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 点赞/取消点赞回复
const handleLikeReply = async (reply: Reply) => {
  try {
    if (reply.isLiked) {
      await reqUnlikeReply(reply.id)
      reply.isLiked = false
      reply.likeCount--
    } else {
      await reqLikeReply(reply.id)
      reply.isLiked = true
      reply.likeCount++
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 显示回复输入框
const handleShowReply = (comment: Comment) => {
  currentReplyComment.value = comment
  replyContent.value = ''
}

// 发送回复
const handleAddReply = async (comment: Comment) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  replyLoading.value = true
  try {
    const result = await reqAddReply({
      commentId: comment.id,
      content: replyContent.value
    })
    if (result.code === 200) {
      ElMessage.success('回复成功')
      replyContent.value = ''
      currentReplyComment.value = null
      // 重新获取评论列表
      getCommentList(1)
    }
  } catch (error: any) {
    ElMessage.error(error.message || '回复失败')
  } finally {
    replyLoading.value = false
  }
}

// 申请领取
const handleClaim = async () => {
  if (!claimForm.value.contactInfo || !claimForm.value.reason) {
    ElMessage.warning('请填写完整信息')
    return
  }

  claimLoading.value = true
  try {
    const result = await reqClaimItem({
      itemId: props.itemId,
      contactInfo: claimForm.value.contactInfo,
      reason: claimForm.value.reason
    })
    if (result.code === 200) {
      ElMessage.success('申请已提交，请等待审核')
      showClaimDialog.value = false
      claimForm.value = { contactInfo: '', reason: '' }
      // 更新本地状态
      if (itemDetail.value) {
        itemDetail.value.status = 1 // 已申领
      }
      emit('refresh')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '申请失败')
  } finally {
    claimLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  itemDetail.value = null
  commentList.value = []
  commentContent.value = ''
  commentPage.value = 1
  currentReplyComment.value = null
  replyContent.value = ''
}

// 格式化日期时间
const formatDateTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

// 获取状态类型
const getStatusType = (status: number) => {
  const types: Record<number, any> = {
    0: 'success',
    1: 'warning',
    2: 'info'
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '待认领',
    1: '已申领',
    2: '已归还'
  }
  return texts[status] || '未知'
}

// 监听对话框打开状态，只在打开时获取数据
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.itemId) {
    getItemDetail()
  }
})
</script>

<style scoped lang="scss">
.detail-container {
  min-height: 400px;
}

.image-gallery {
  .el-carousel {
    height: 400px;

    :deep(.el-carousel__item) {
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
    }

    .el-image {
      max-width: 100%;
      max-height: 100%;
    }
  }
}

.detail-info {
  .detail-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 15px 0;
    color: #303133;
  }

  .el-tag {
    margin-bottom: 20px;
  }

  .detail-desc {
    margin-bottom: 20px;

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .description {
      line-height: 1.6;
      white-space: pre-wrap;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.comment-section {
  margin-top: 30px;
}

.add-comment {
  margin-bottom: 30px;
}

.comment-list {
  .comment-item {
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;

    .comment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .comment-user {
        display: flex;
        align-items: center;
        gap: 10px;

        .user-meta {
          display: flex;
          flex-direction: column;

          .user-name {
            font-weight: 500;
            color: #303133;
          }

          .comment-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }

      .comment-actions {
        display: flex;
        gap: 5px;
      }
    }

    .comment-content {
      margin-left: 46px;
      line-height: 1.6;
      color: #606266;
    }
  }
}

.reply-list {
  margin: 15px 0 0 46px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;

  .reply-item {
    padding: 8px 0;

    &:not(:last-child) {
      border-bottom: 1px solid #e4e7ed;
    }

    .reply-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 5px;
      font-size: 13px;

      .reply-user {
        font-weight: 500;
        color: #303133;
      }

      .reply-to {
        color: #409eff;
      }

      .reply-time {
        color: #909399;
        margin-left: auto;
      }
    }

    .reply-content {
      margin-left: 36px;
      line-height: 1.5;
      color: #606266;
      font-size: 13px;
    }
  }
}

.reply-input {
  margin: 10px 0 0 46px;

  .reply-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 10px;
  }
}

.load-more {
  width: 100%;
  margin-top: 20px;
}
</style>

